package com.guo.rpc.config;

import com.guo.rpc.annotation.Service;
import com.guo.rpc.bean.ServiceBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * @Author: ljguo4
 * @email: ljguo4@iflytek.com
 * @Date: 2021/7/22 11:21
 * @Description:
 * @version: 1.0
 */
@Configuration
public class RpcProviderAutoConfigration {

    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    public void init() {
        Map<String, Object> beanMap = this.applicationContext.getBeansWithAnnotation(Service.class);

        for (Map.Entry<String, Object> entry : beanMap.entrySet()) {
            String beanName = entry.getKey();
            Object bean = entry.getValue();

            this.initProviderBean(beanName, bean);
        }
    }

    private void initProviderBean(String beanName, Object bean) {
        Service service = this.applicationContext.findAnnotationOnBean(beanName, Service.class);

        // 服务指定的接口类
        Class<?> interfaceClass = service.interfaceClass();
        if (interfaceClass == Void.class) {
            // 说明没有设置，这时去类实现的第一个接口
            Class<?> beanClass = bean.getClass();
            Class<?>[] interfaces = beanClass.getInterfaces();

            interfaceClass = interfaces.length > 0 ? interfaces[0] : null;
        }
        String version = service.version();

        ServiceBean serviceBean = new ServiceBean();
        serviceBean.setRef(bean);
        serviceBean.setInterfaceClass(interfaceClass);
        serviceBean.setApplicationContext(this.applicationContext);
        serviceBean.setVersion(version);

        // 暴露服务
        serviceBean.export();
    }
}
